package com.imarad.server.bio;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.imarad.server.common.ClientPacket;
import com.imarad.server.common.Constants;

/**
 * @author hhu 【huan.hu@cnambition.com】
 * @version com.imarad.server.bio, v 0.1 2018/2/1 12:00 hhu Exp $$
 */
public class BioServerHandler implements Runnable {
    /**
     * 日志工具
     */
    private static final Logger LOG = LoggerFactory.getLogger(BioServerHandler.class);
    private Socket              socket;

    private boolean             isRun;

    private String              info;

    public BioServerHandler(Socket socket, String info) {
        this.socket = socket;
        this.info = info;
    }

    @Override
    public void run() {
        isRun = true;
        try {
            Date date = new Date();
            byte[] buff;
            int eof;
            while (isRun) {
                buff = new byte[Constants.PACKET_HEADER_LEN];
                eof = socket.getInputStream().read(buff, 0, buff.length);
                if (eof == -1) {
                    continue;
                }
                ClientPacket packet = new ClientPacket(buff);
                buff = new byte[packet.getPacketLen()];
                eof = socket.getInputStream().read(buff, 0, buff.length);
                if (eof == -1) {
                    continue;
                }
                packet.setData(buff);
                LOG.debug("接收到{},消息:{}", info, new String(packet.getData()));
                date.setTime(System.currentTimeMillis());
                handleMessage(createSendPacket("收到你的消息:" + date));
            }
        } catch (IOException e) {
            if (isRun) {
                LOG.error("服务端异常", e);
                isRun = false;
            } else {
                LOG.info("{}已经断开连接", info);
            }
        }
    }

    /**
     * 处理一个客户端socket连接
     *
     * @throws IOException
     */
    private void handleMessage(ClientPacket packet) throws IOException {
        // 流：客户端->服务端（读）
        // 流：服务端->客户端（写）

        byte[] buff = packet.getSendData();
        LOG.debug("发送数据：{}", Arrays.toString(buff));
        OutputStream out = socket.getOutputStream();
        out.write(buff);
        out.flush();
    }

    private ClientPacket createSendPacket(String info) {
        ClientPacket packet = new ClientPacket();
        byte[] buff = info.getBytes();
        packet.setCommand(Constants.SEND_MSG_COMMAND);
        packet.setPacketId(1);
        packet.setPacketCount(1);
        packet.setPacketLen(buff.length);
        packet.setTotalLen(buff.length);
        packet.setData(buff);
        return packet;
    }

    private void close() {
        if (socket != null && socket.isConnected()) {
            try {
                isRun = false;
                socket.close();
                socket = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}